package com.cloudlibrary.controller;

import com.cloudlibrary.domain.Book;
import com.cloudlibrary.domain.User;
import com.cloudlibrary.entity.PageResult;
import com.cloudlibrary.entity.Result;
import com.cloudlibrary.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;


    @RequestMapping("/selectNewbooks")
    public ModelAndView selectNewBooks(){
        int pageNum = 1;
        int pageSize = 5;
        PageResult pageResult =
                bookService.selectNewBooks(pageNum,pageSize);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("books_new");
        modelAndView.addObject("pageResult",pageResult);
        return modelAndView;
    }
    @ResponseBody
    @RequestMapping("/book/findById")
    public Result<Book> findById(String id){
        try{
            Book book = bookService.findById(id);
            if (book == null){
                return new Result<>(false,"查询图书失败1");
            }
            return new Result<>(true,"查询图书成功",book);
        }catch (Exception e){
            e.printStackTrace();
            return new Result<>(false,"查询图书失败！2");
        }
    }
    @ResponseBody
    @RequestMapping("/book/borrowBook")
    public Result borrowBook(Book book, HttpSession session){
        String pname =
                ((User)session.getAttribute("USER_SESSION")).getName();
        book.setBorrower(pname);
        try {
            Integer count = bookService.borrowBook(book);
            if (count == null){
                return new Result(false,"借阅图书失败！1");
            }
            return new Result(true,"借阅成功，请到行政中心取书");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"借阅图书失败！2");
        }
    }
}
